import 'package:fakegpt/api/ChatGptApi.dart';
import 'package:fakegpt/page/home/state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class HomeLogic extends GetxController {
  HomeState state = HomeState();
  Future<void> onRefresh() async {
    state.list.clear();
    try {
      state.list.addAll(await ChatGptApi.getConversationList() ?? []);
      state.refreshController.refreshCompleted();
    } catch (e) {
      state.refreshController.refreshFailed();
      Get.snackbar("提示", "获取失败", colorText: Colors.white);
      print(e);
    }
    update(['list']);
  }

  HomeLogic() {}

  Future<void> deleteConversation(String id) async {
    if (id.isEmpty) return;
    EasyLoading.show(status: "删除中..");
    try {
      await ChatGptApi.deleteConversation(id);
    } catch (e) {
      print(e);
      Get.snackbar("提示", "删除失败", colorText: Colors.white);
    }
    EasyLoading.dismiss();
    state.refreshController.requestRefresh();
  }

  void rename(String id) {
    var controller = TextEditingController();
    Get.defaultDialog(
        title: "重命名",
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(hintText: "请输入新标题"),
        ),
        actions: [
          TextButton(
              onPressed: () {
                Get.back();
              },
              child: Text(
                "取消",
                style: TextStyle(color: Colors.red.shade200),
              )),
          TextButton(
              onPressed: () async {
                if (controller.text.isEmpty) {
                  return;
                }
                Get.back();
                EasyLoading.show(status: "修改中");
                try {
                  await ChatGptApi.rename(id: id, title: controller.text);
                } catch (e) {
                  Get.snackbar("提示", "修改失败", colorText: Colors.white);
                  print(e);
                }
                EasyLoading.dismiss();
                state.refreshController.requestRefresh();
              },
              child: const Text("确定")),
        ]);
  }
}
